<template>
    <div id="login" style="-webkit-app-region: drag; -webkit-user-select: none">
        <div class="login-img align-center">
            <img src="../../assets/img/login/login_icon.png" alt />
            <div class="cp-name">美丽科学教学平台</div>
            <div class="grade-level">
                <img :src="loginImg" alt="" />
            </div>
            <div class="app-explanation">
                <div>*本平台内容已通过国家数字教育资源公共服务体系备案认证</div>
                <div v-if="eduLevel === 'primary'">
                    *教育科学出版社唯一授权联合开发教科版《科学》课程资源平台
                </div>
            </div>
        </div>
        <div class="login-form">
            <div class="top-icon flex-end margin-r-10" style="-webkit-app-region: no-drag">
                <div class="border-dotted flex-center" @click="miniWindow">
                    <img src="../../assets/img/login/tominisize.png" alt />
                </div>
                <div class="border-dotted flex-center" @click="closeWindow">
                    <img src="../../assets/img/login/close.png" alt />
                </div>
            </div>
            <div></div>
            <div class="form-container" style="-webkit-app-region: no-drag">
                <div class="login-tips flex-center">
                    <div class="user-message">
                        <div class="title-content flex-center jus-between">
                            <div class="content-tips">
                                <div class="title-item text-left s-32">{{ computeTitle }}</div>
                                <div class="title-tips text-left s-14" v-if="this.register !== 0">
                                    {{ computeNote }}
                                </div>
                            </div>
                            <div class="img flex-center" @click="changeLoginMethod" v-if="!register">
                                <div class="img-tips" v-if="this.register === 0">
                                    {{ computeNote }}
                                </div>
                                <img v-if="loginMethod" src="../../assets/img/login/code.png" alt />
                                <img v-else src="../../assets/img/login/computer_icon.png" alt />
                            </div>
                        </div>
                    </div>
                </div>
                <div v-show="register === 0">
                    <login-username v-show="loginMethod" ref="loginUser" v-on:changeRegister="changeRegister(2)">
                    </login-username>
                    <login-code v-bind:qrImag="qrImag" v-if="!loginMethod"></login-code>
                </div>
                <register v-if="register !== 0" v-on:loginByAccount="loginByAccount" v-bind:submitBtn="registerBtn"
                    v-on:changeRegister="changeRegister(0)"></register>
            </div>
            <div class="bottom-tips text-center" style="-webkit-app-region: no-drag">
                <div class="tips" @click="switchInfo">
                    {{ register !== 0 ? "已有账号？点击登录" : "没有账号？点击注册" }}
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import loginUsername from "./Loginbyusername";
import loginCode from "./Codelogin";
import register from "./Register";
import qrCode from "qrcode";
import store from '@/content/store/index.js'
import user from "@/content/api/user";
import { StringUtil } from "../../../../../static/utils/StringUtil";
import { User } from "../../../../../static/lib/sqlite/model/User";
import { SqlLib } from "../../../../../static/lib/sqlite/SqlLib";
import moment from "moment";
import { Ini } from "../../utils/ini";
const cryUtil = require("../../../../../static/utils/CrypUtil");

export default {
    components: { loginUsername, loginCode, register },
    provide () {
        return {
            checkLoginPage: this.checkLoginPage,
        };
    },
    data () {
        return {
            loginMethod: true,
            register: 0, //0-登录；1-注册；2-忘记密码
            color: false,
            qrImag: "",
            qrUuid: "",
            eduLevel: Ini.readIni("data", "eduLevel"),
        };
    },
    computed: {
        loginImg () {
            if (this.eduLevel === "primary") {
                return require("../../assets/img/login/home-ca.png");
            } else {
                return require("../../assets/img/login/ver-ms.png");
            }
        },
        computeTitle: function () {
            if (this.register === 0) {
                return `登录账号`;
            } else if (this.register === 1) {
                return "注册账号";
            } else {
                return "忘记密码";
            }
        },
        computeNote: function () {
            if (this.register === 0) {
                if (this.loginMethod) {
                    return "扫码登录";
                }
                return "账号登录";
            } else if (this.register === 1) {
                return "请按照提示填写注册信息";
            } else {
                return "请按照提示找回密码";
            }
        },
        registerBtn: function () {
            if (this.register === 0) {
                return "";
            } else if (this.register === 1) {
                return "注册";
            } else {
                return "找回密码";
            }
        },
    },
    mounted () {
        window.document.onselectstart = () => false;
        let dom = document.getElementsByClassName("el-input__suffix")[0];
        dom.addEventListener("click", () => {
            this.$nextTick(() => {
                let icon = document.getElementsByClassName("el-input__icon")[0];
                !this.color
                    ? (icon.style.color = "#4894FF")
                    : (icon.style.color = "#909298");
                this.color = !this.color;
            });
        });
    },
    beforeDestroy () {
        if (window.queryUser) {
            clearInterval(window.queryUser);
        }
    },
    methods: {
        switchInfo () {
            if (this.register === 0) {
                this.register = 1;
            } else {
                this.register = 0;
            }
        },
        changeLoginMethod () {
            let _this = this;
            _this.loginMethod = !_this.loginMethod;
            if (!this.loginMethod) {
                let version = _this.$readIniFile("data", "versionInfo");
                let env = _this.$readIniFile("data", "env");
                let envDomain =
                    env === _this.$CONST.global.developmentStr
                        ? _this.$CONST.global.developmentWxDomain
                        : _this.$CONST.global.productionWxDomain;
                const params = {
                    clientVersion: version,
                };
                user.getQrUuid(params).then((res) => {
                    _this.qrUuid = res.returnValue.qrUuid;
                    let chatUrl = StringUtil.format(
                        "https://{0}/scanLogin/wxAuth.html?qr_uuid={1}",
                        envDomain,
                        _this.qrUuid
                    );
                    this.createQr(chatUrl);
                });
            }
        },
        createQr (resUrl) {
            let _this = this;
            let opts = {
                errorCorrectionLevel: "L",
                type: "image/jpeg",
                margin: 0,
                scale: 10,
            };
            qrCode.toDataURL(resUrl, opts, function (err, url) {
                if (err) {
                    _this.qrImag = "";
                } else {
                    _this.checkQrState();
                    _this.qrImag = url;
                }
            });
        },
        miniWindow () {
            this.$client.minimise();
        },
        closeWindow () {
            this.$client.closeAllWindow();
        },
        checkQrState () {
            let _this = this;
            window.queryUser = setInterval(function () {
                const params = {
                    qrUuid: _this.qrUuid,
                };
                user
                    .getQrUserInfo(params)
                    .then((res) => {
                        if (res.code == 0) {
                            if (window.queryUser) {
                                clearTimeout(window.queryUser);
                            }
                            if (
                                res.returnValue.isOverLimit &&
                                res.returnValue.isOverLimit == 1
                            ) {
                                _this
                                    .$dialog({
                                        title: "提示",
                                        confirm: "确定",
                                        type: "success",
                                        message: "您的账号正在重复登录，其他登录地点即将下线",
                                    })
                                    .then((value) => {
                                        if (value) {
                                            //确定按钮
                                            localStorage.setItem(
                                                "accesstoken",
                                                res.returnValue.accessToken
                                            );
                                            localStorage.setItem(
                                                "refreshToken",
                                                res.returnValue.refreshToken
                                            );
                                            _this.getUserInfo();
                                        }
                                    })
                                    .catch((err) => {
                                        console.log(err);
                                    });
                            } else {
                                localStorage.setItem(
                                    "accesstoken",
                                    res.returnValue.accessToken
                                );
                                localStorage.setItem(
                                    "refreshToken",
                                    res.returnValue.refreshToken
                                );
                                _this.getUserInfo();
                            }
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }, 1000);
        },
        //获取用户信息
        getUserInfo () {
            let _this = this;
            let offlineUseTime = this.$readIniFile("data", "ofuTime");
            user
                .getUserInfo()
                .then((response) => {
                    if (response.returnValue.isVip === "2") {
                        store.state.becomeVip = false
                    }else{
                        store.state.becomeVip = true
                    }
                    if (response.code == "0") {
                        let resUser = response.returnValue;
                        let user = new User();
                        user.id = resUser.userBaseVO.userId;
                        user.name = resUser.userBaseVO.fullName
                            ? resUser.userBaseVO.fullName
                            : "";
                        user.mobile = resUser.userBaseVO.mobile
                            ? resUser.userBaseVO.mobile
                            : "";
                        user.avatar = resUser.userBaseVO.avatar
                            ? resUser.userBaseVO.avatar
                            : "";
                        user.limitCount = resUser.userBaseVO.limitCount
                            ? resUser.userBaseVO.limitCount
                            : 1;
                        user.schoolName = resUser.schoolName ? resUser.schoolName : "";
                        user.isGlobal = resUser.isGlobal ? resUser.isGlobal : "";
                        user.schoolId = resUser.schoolId ? resUser.schoolId : "";
                        user.eduLevelId = resUser.eduLevelId ? resUser.eduLevelId : "";
                        user.vipType = cryUtil.aesEncrypt(
                            resUser.isVip + "",
                            user.id + "",
                            true
                        );
                        user.remainderDays = cryUtil.aesEncrypt(
                            resUser.days + "",
                            user.id + "",
                            true
                        );
                        user.activeTime = moment().format("YYYY-MM-DD HH:mm:ss");
                        user.bookId = resUser.bookId ? resUser.bookId : "";
                        user.offlineExpired = offlineUseTime
                            ? offlineUseTime
                            : _this.$CONST.global.offlineDefaultDays;
                        user.offlineExpired = cryUtil.aesEncrypt(
                            user.offlineExpired + "",
                            user.id + "",
                            true
                        );

                        //更新用户信息
                        let sqlInstance = SqlLib.getInstance(window.$DBDIR);
                        let result = sqlInstance.updateOrInsertObjectById(user);
                        console.log(result);
                        if (sqlInstance.checkSqlError(result)) {
                            //需要重新检测网络
                            window.netStatus = false;
                            _this.$router.push({ name: "home" });
                        } else {
                            _this.$message.error("登录异常！");
                        }
                    } else {
                        _this.$message(response.message);
                    }
                })
                .catch((error) => {
                    _this.$message.error("登录失败！");
                });
        },
        loginByAccount (account) {
            this.$refs.loginUser.goLogin(account.loginName, account.password, true);
        },
        changeRegister (num) {
            this.register = num;
        },
        checkLoginPage () {
            //检查是否是登录页面
            return this.register === 0 && this.loginMethod;
        },
    },
};
</script>

<style lang="scss">
#login {
    width: 100vw;
    height: 100vh;
    display: flex;

    .login-img {
        background-image: url(../../assets/img/login/login_bg.png);
        background-size: cover;
        background-repeat: no-repeat;
        width: 100vh;
        height: 100vh;
        position: relative;
        img {
            width: 351px;
            height: 168px;
        }
        .cp-name {
            width: 273px;
            height: 27px;
            line-height: 27px;
            text-align: justify;
            text-align-last: justify;
            margin-top: 23px;
            margin-bottom: 15px;
            font-size: 26px;
            color: rgba(255, 255, 255, 1);
        }
        .grade-level {
            width: 280px;
            height: 34px;
            img {
                width: 100%;
                height: 100%;
            }
        }
        .app-explanation {
            position: absolute;
            width: 100%;
            left: 0;
            bottom: 0;
            padding-bottom: 5vh;
            display: flex;
            justify-content: flex-end;
            align-items: flex-end;
            flex-direction: column;
            div {
                color: #fff;
                font-size: 12px;
                width: 350px;
                margin-bottom: 5px;
            }
        }
    }
    .form-container {
        flex: 1;
        margin-top: 16.3vw;
    }
    .login-form {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
        flex: 1;
        .top-icon {
            margin-top: 12px;
            padding-right: 7px;
            width: 100%;
            .border-dotted {
                margin-right: 12px;
                width: 14px;
                height: 14px;
                img {
                    width: 12px;
                    height: 12px;
                }
            }
        }
    }
    .login-tips {
        /*margin-top: 16.3vw;*/
        margin-bottom: 1.5vw;
        .img-tips {
            background-image: url(../../assets/img/login/login-tips.png);
            background-size: cover;
            width: 70px;
            height: 28px;
            padding-left: 8px;
            line-height: 28px;
            margin-right: 12px;
            color: #eaa13a;
            font-size: 12px;
        }
    }
    .user-message {
        width: 25vw;
    }
    .title-content {
        width: 25vw;
        margin: 0 auto;
        .title-item {
            font-weight: 400;
            color: #2f3032;
            line-height: 2.8vw;
        }
        .title-tips {
            font-weight: 400;
            color: #909297;
            line-height: 40px;
            height: 40px;
            width: 100%;
        }
        img {
            width: 56px;
            height: 56px;
            border-radius: 50%;
        }
    }
    .bottom-tips {
        font-size: 1.2vw;
    }
}
</style>
